<template>
  <div class="search-function">
    <!-- 顶部导航栏 -->
    <div class="search-header">
      <div class="header-content">
        <div class="header-left">
          <div class="logo-section">
            <el-icon size="28" class="logo-icon"><Camera /></el-icon>
            <h1 class="page-title">智能搜题</h1>
          </div>
          <p class="page-subtitle">拍照即搜，秒出答案</p>
        </div>
        <div class="header-right">
          <el-badge :value="searchHistory.length" class="history-badge">
            <el-button circle @click="showHistory = true">
              <el-icon><Clock /></el-icon>
            </el-button>
          </el-badge>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 - 可滚动 -->
    <div class="search-main-container">
      <div class="search-main">
      <!-- 搜题方式选择卡片 -->
      <div class="search-modes">
        <div
          class="mode-card"
          :class="{ active: searchMode === 'camera' }"
          @click="searchMode = 'camera'"
        >
          <div class="mode-icon">
            <el-icon size="32"><Camera /></el-icon>
          </div>
          <h3>拍照搜题</h3>
          <p>拍摄题目照片，AI智能识别</p>
        </div>

        <div
          class="mode-card"
          :class="{ active: searchMode === 'text' }"
          @click="searchMode = 'text'"
        >
          <div class="mode-icon">
            <el-icon size="32"><Edit /></el-icon>
          </div>
          <h3>文字搜题</h3>
          <p>手动输入题目内容</p>
        </div>
      </div>

      <!-- 搜题内容区域 -->
      <div class="search-content">
        <!-- 拍照搜题 -->
        <div v-if="searchMode === 'camera'" class="camera-section">
          <div class="upload-container">
            <div v-if="!uploadedImage" class="upload-area" @click="triggerFileInput">
              <div class="upload-placeholder">
                <el-icon size="64" class="upload-icon"><Plus /></el-icon>
                <h3>点击拍照或上传图片</h3>
                <p>支持 JPG、PNG 格式，文件大小不超过 10MB</p>
                <div class="upload-buttons">
                  <el-button type="primary" size="large">
                    <el-icon><Camera /></el-icon>
                    拍照
                  </el-button>
                  <el-button size="large">
                    <el-icon><Upload /></el-icon>
                    选择图片
                  </el-button>
                </div>
              </div>
            </div>
            
            <div v-else class="image-preview">
              <div class="preview-container">
                <img :src="uploadedImage" alt="题目图片" class="preview-image" />
                <div class="image-overlay">
                  <el-button circle @click="clearImage" class="clear-btn">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
              </div>
              
              <div class="image-actions">
                <el-button 
                  type="primary" 
                  size="large" 
                  :loading="searching"
                  @click="performImageSearch"
                  class="search-btn"
                >
                  <el-icon><Search /></el-icon>
                  {{ searching ? '识别中...' : '开始搜题' }}
                </el-button>
              </div>
            </div>
            
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              @change="handleFileSelect" 
              style="display: none"
            />
          </div>
        </div>

        <!-- 文字搜题 -->
        <div v-if="searchMode === 'text'" class="text-section">
          <div class="text-input-container">
            <el-input
              v-model="questionText"
              type="textarea"
              :rows="8"
              placeholder="请输入题目内容，支持数学公式、化学方程式等..."
              class="question-textarea"
              show-word-limit
              maxlength="1000"
            />
            
            <div class="text-actions">
              <el-button 
                type="primary" 
                size="large" 
                :loading="searching"
                :disabled="!questionText.trim()"
                @click="performTextSearch"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
                {{ searching ? '搜索中...' : '开始搜题' }}
              </el-button>
            </div>
          </div>
        </div>


      </div>
    </div>

    <!-- 搜题结果区域 -->
    <div v-if="searchResult" class="result-section">
      <div class="result-header">
        <div class="result-title">
          <el-icon class="result-icon"><Check /></el-icon>
          <h2>搜题结果</h2>
        </div>
        <div class="result-actions">
          <el-button type="text" @click="addToFavorites" :disabled="isFavorited">
            <el-icon><Star /></el-icon>
            {{ isFavorited ? '已收藏' : '收藏' }}
          </el-button>
          <el-button type="text" @click="shareResult">
            <el-icon><Share /></el-icon>
            分享
          </el-button>
          <el-button type="text" @click="copyResult">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
        </div>
      </div>

      <div class="result-content">
        <!-- OCR识别结果展示 -->
        <div v-if="searchResult.ocrText" class="ocr-result-card">
          <div class="ocr-header">
            <el-icon class="ocr-icon"><Document /></el-icon>
            <span class="ocr-title">图片识别文字</span>
          </div>
          <div class="ocr-text-content">
            {{ searchResult.ocrText }}
          </div>
        </div>

        <!-- 题目和答案展示 -->
        <div class="qa-container">
          <!-- 题目 -->
          <div class="question-section">
            <div class="section-header">
              <el-icon class="section-icon question-icon"><QuestionFilled /></el-icon>
              <span class="section-title">题目</span>
            </div>
            <div class="question-content">
              {{ searchResult.question }}
            </div>
          </div>

          <!-- 答案 -->
          <div class="answer-section">
            <div class="section-header">
              <el-icon class="section-icon answer-icon"><Check /></el-icon>
              <span class="section-title">答案解析</span>
              <el-tag type="success" size="small" class="ai-tag">AI解答</el-tag>
            </div>
            <div class="answer-content" v-html="formatAnswer(searchResult.answer)"></div>
          </div>
        </div>

        <!-- 解题思路 -->
        <div v-if="searchResult.analysis" class="analysis-section">
          <div class="section-header">
            <el-icon class="section-icon analysis-icon"><InfoFilled /></el-icon>
            <span class="section-title">解题思路</span>
          </div>
          <div class="analysis-content" v-html="formatAnswer(searchResult.analysis)"></div>
        </div>

        <!-- 相关题目推荐 -->
        <div v-if="relatedQuestions.length > 0" class="related-section">
          <h3>相关题目推荐</h3>
          <div class="related-questions">
            <div
              v-for="question in relatedQuestions"
              :key="question.id"
              class="related-item"
              @click="selectRelatedQuestion(question)"
            >
              <div class="related-content">
                <div class="related-question">{{ question.question || question.title }}</div>
                <div v-if="question.answer" class="related-answer">答案：{{ question.answer }}</div>
              </div>
              <el-icon class="related-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜题历史抽屉 -->
    <el-drawer v-model="showHistory" title="搜题历史" size="400px">
      <div class="history-content">
        <div v-if="searchHistory.length === 0" class="empty-history">
          <el-icon size="64"><DocumentRemove /></el-icon>
          <p>暂无搜题历史</p>
        </div>
        
        <div v-else class="history-list">
          <div 
            v-for="item in searchHistory" 
            :key="item.id"
            class="history-item"
            @click="loadHistoryItem(item)"
          >
            <div class="history-question">{{ item.question }}</div>
            <div class="history-time">{{ formatTime(item.timestamp) }}</div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 回到顶部按钮 -->
    <el-backtop
      :right="40"
      :bottom="40"
      :visibility-height="300"
      target=".search-main-container"
    >
      <div class="back-to-top">
        <el-icon><ArrowUp /></el-icon>
      </div>
    </el-backtop>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, CopyDocument, Delete, Camera, Edit, Plus, Upload, Close,
  Clock, Star, Share, QuestionFilled, Check, InfoFilled, ArrowRight,
  DocumentRemove, Document, ArrowUp
} from '@element-plus/icons-vue'
import { searchByImage, searchByText, ocrImage } from '@/api/tutor'
import { getUserInfo } from '@/utils/auth'

// 定义事件
const emit = defineEmits(['search-result'])

// 状态管理
const searchMode = ref('camera')
const searching = ref(false)
const uploadedImage = ref('')
const questionText = ref('')
const searchResult = ref(null)
const showHistory = ref(false)
const searchHistory = ref([])
const relatedQuestions = ref([])
const fileInput = ref(null)

// 用户信息
const userInfo = getUserInfo()

// 计算属性
const isFavorited = computed(() => {
  // 这里可以检查当前题目是否已收藏
  return false
})

// 文件上传相关方法
const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 检查文件大小
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过10MB')
      return
    }

    // 转换为base64
    const reader = new FileReader()
    reader.onload = (e) => {
      uploadedImage.value = e.target.result
      ElMessage.success('图片上传成功')
    }
    reader.readAsDataURL(file)
  }
}

const clearImage = () => {
  uploadedImage.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}



// 结果处理方法
const addToFavorites = () => {
  ElMessage.success('已添加到收藏夹')
}

const shareResult = () => {
  ElMessage.info('分享功能开发中...')
}

const selectRelatedQuestion = (question) => {
  console.log('🎯 选择了相关题目:', question)

  // 将相关题目设置为当前搜题结果
  searchResult.value = {
    id: 'related_' + Date.now(),
    question: question.question || question.title,
    answer: question.answer || '暂无答案',
    analysis: question.explanation || '暂无解析',
    timestamp: Date.now()
  }

  // 保存到历史记录
  saveToHistory(searchResult.value)

  // 滚动到结果区域
  nextTick(() => {
    const resultSection = document.querySelector('.result-section')
    if (resultSection) {
      resultSection.scrollIntoView({ behavior: 'smooth' })
    }
  })

  ElMessage.success('已加载相关题目')
}

// 历史记录相关方法
const loadHistoryItem = (item) => {
  searchResult.value = item
  showHistory.value = false
  ElMessage.success('已加载历史记录')
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString()
}

// 执行图片搜题
const performImageSearch = async () => {
  if (!uploadedImage.value) {
    ElMessage.warning('请先上传题目图片')
    return
  }

  searching.value = true

  // 显示进度提示
  const loadingMessage = ElMessage({
    message: '正在分析图片，请稍候...',
    type: 'info',
    duration: 0, // 不自动关闭
    showClose: true
  })

  try {
    console.log('🚀 开始图片搜题，用户ID:', userInfo?.id)

    // 直接调用一体化搜题接口
    const response = await searchByImage({
      imageData: uploadedImage.value,
      userId: userInfo?.id || 1,
      sessionName: '拍照搜题'
    })

    console.log('📄 搜题API响应:', response)

    if (response.success || response.code === 200) {
      const data = response.data || response
      console.log('🔍 后端返回的完整数据:', data)

      // 处理后端返回的数据结构
      let questionText = data.question || data.ocrText || '图片搜题结果'
      let answerText = ''
      let analysisText = ''
      let ocrText = ''
      let ocrLatex = ''

      // 提取OCR识别结果
      if (data.ocrText) {
        ocrText = extractPureTextFromOcr(data.ocrText)
        console.log('✅ OCR识别结果:', ocrText)
      }

      // 提取LaTeX公式（如果有）
      if (data.ocrLatex || data.latex) {
        ocrLatex = data.ocrLatex || data.latex
        console.log('✅ LaTeX公式:', ocrLatex)
      }

      // 处理analysis对象
      if (data.analysis && typeof data.analysis === 'object') {
        const analysisObj = data.analysis

        // 提取答案信息
        answerText = analysisObj.finalAnswer || analysisObj.answer || analysisObj.solutionSteps || '搜题结果处理中...'

        // 提取分析信息
        analysisText = analysisObj.analysis || analysisObj.detailedAnalysis || analysisObj.explanation || ''

        // 如果有解题步骤，添加到分析中
        if (analysisObj.solutionSteps && analysisObj.solutionSteps !== answerText) {
          analysisText = analysisObj.solutionSteps + (analysisText ? '\n\n' + analysisText : '')
        }

        // 提取知识点和难度信息
        if (analysisObj.knowledgePoints) {
          analysisText += `\n\n知识点：${analysisObj.knowledgePoints}`
        }
        if (analysisObj.difficultyLevel) {
          analysisText += `\n难度等级：${analysisObj.difficultyLevel}/5`
        }
      } else {
        // 兼容旧格式
        answerText = data.answer || data.response || data.aiAnalysis || '搜题结果处理中...'
        analysisText = data.analysis || data.explanation || data.studyTips || ''
      }

      searchResult.value = {
        id: data.questionId || data.id || 'search_' + Date.now(),
        question: questionText,
        answer: answerText,
        analysis: analysisText,
        ocrText: ocrText,
        ocrLatex: ocrLatex,
        timestamp: Date.now()
      }

      console.log('✅ 处理后的搜题结果:', searchResult.value)

      // 处理相似题目数据
      if (data.similarQuestions && Array.isArray(data.similarQuestions)) {
        console.log('🔍 后端返回的相似题目:', data.similarQuestions)
        relatedQuestions.value = data.similarQuestions.map((item, index) => ({
          id: index + 1,
          title: item.question || '相似题目',
          question: item.question,
          answer: item.answer,
          explanation: item.explanation
        }))
        console.log('✅ 处理后的相似题目:', relatedQuestions.value)
      } else {
        console.log('⚠️ 没有相似题目数据，使用默认推荐')
        generateRelatedQuestions()
      }

      // 保存到历史记录
      saveToHistory(searchResult.value)

      emit('search-result', searchResult.value)

      loadingMessage.close()
      ElMessage.success('搜题成功！')
    } else {
      throw new Error(response.message || '搜题失败')
    }
  } catch (error) {
    console.error('❌ 图片搜题失败:', error)

    loadingMessage.close()

    // 根据错误类型显示不同的提示
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接或稍后重试')
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后重试')
    } else {
      ElMessage.error('搜题服务暂不可用，请稍后重试')
    }

    // 清空搜题结果
    searchResult.value = null
    relatedQuestions.value = []
  } finally {
    searching.value = false
  }
}

// 执行文字搜题
const performTextSearch = async () => {
  if (!questionText.value.trim()) {
    ElMessage.warning('请输入题目内容')
    return
  }

  searching.value = true

  try {
    const response = await searchByText({
      question: questionText.value,
      userId: userInfo?.id || 1
    })

    if (response.success || response.code === 200) {
      const data = response.data || response
      searchResult.value = {
        id: data.id || 'search_' + Date.now(),
        question: questionText.value,
        answer: data.answer || data.response || '搜题结果处理中...',
        analysis: data.analysis || data.explanation || '',
        timestamp: Date.now()
      }

      saveToHistory(searchResult.value)
      generateRelatedQuestions()
      emit('search-result', searchResult.value)
      ElMessage.success('搜题成功！')
    } else {
      throw new Error(response.message || '搜题失败')
    }
  } catch (error) {
    console.error('❌ 文字搜题失败:', error)

    // 根据错误类型显示不同的提示
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接或稍后重试')
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后重试')
    } else {
      ElMessage.error('搜题服务暂不可用，请稍后重试')
    }

    // 清空搜题结果
    searchResult.value = null
    relatedQuestions.value = []
  } finally {
    searching.value = false
  }
}

// 保存到历史记录
const saveToHistory = (result) => {
  const historyItem = {
    ...result,
    timestamp: Date.now()
  }

  // 添加到历史记录开头
  searchHistory.value.unshift(historyItem)

  // 保持最多20条历史记录
  if (searchHistory.value.length > 20) {
    searchHistory.value = searchHistory.value.slice(0, 20)
  }

  // 保存到localStorage
  try {
    localStorage.setItem('search_history', JSON.stringify(searchHistory.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 生成相关题目推荐（仅在没有后端数据时使用）
const generateRelatedQuestions = () => {
  // 如果后端没有返回相似题目，则清空推荐
  relatedQuestions.value = []
  console.log('⚠️ 后端未返回相似题目数据')
}

// 格式化答案显示
const formatAnswer = (answer) => {
  if (!answer) return ''

  // 如果是字符串，直接处理
  if (typeof answer === 'string') {
    return answer.replace(/\n/g, '<br>')
  }

  // 如果是对象，尝试提取有用信息
  if (typeof answer === 'object') {
    if (answer.content) return answer.content.replace(/\n/g, '<br>')
    if (answer.text) return answer.text.replace(/\n/g, '<br>')
    if (answer.explanation) return answer.explanation.replace(/\n/g, '<br>')
    if (answer.message) return answer.message.replace(/\n/g, '<br>')

    // 如果是数组，连接成字符串
    if (Array.isArray(answer)) {
      return answer.join('<br>')
    }

    // 最后尝试JSON字符串化，但格式化显示
    try {
      return JSON.stringify(answer, null, 2).replace(/\n/g, '<br>').replace(/"/g, '')
    } catch (e) {
      return '数据格式错误'
    }
  }

  // 其他类型转换为字符串
  return String(answer).replace(/\n/g, '<br>')
}

// 复制结果
const copyResult = async () => {
  if (!searchResult.value) return

  const text = `题目：${searchResult.value.question}\n\n答案：${searchResult.value.answer}\n\n解题思路：${searchResult.value.analysis || '无'}`

  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('结果已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 清除结果
const clearResult = () => {
  searchResult.value = null
  relatedQuestions.value = []
}

// 初始化时加载历史记录
const loadHistory = () => {
  try {
    const saved = localStorage.getItem('search_history')
    if (saved) {
      searchHistory.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 从OCR结果中提取纯文字内容
const extractPureTextFromOcr = (ocrResult) => {
  if (!ocrResult) return ''

  // 如果已经是纯文字，直接返回
  if (typeof ocrResult === 'string') {
    try {
      // 尝试解析JSON
      const parsed = JSON.parse(ocrResult)
      return extractTextFromParsedOcr(parsed)
    } catch (e) {
      // 不是JSON，直接返回文字
      return ocrResult.trim()
    }
  }

  // 如果是对象，提取文字内容
  if (typeof ocrResult === 'object') {
    return extractTextFromParsedOcr(ocrResult)
  }

  return String(ocrResult).trim()
}

// 从解析后的OCR对象中提取文字
const extractTextFromParsedOcr = (ocrObj) => {
  if (!ocrObj) return ''

  // 阿里云OCR格式：直接提取content字段
  if (ocrObj.content) {
    return ocrObj.content.trim()
  }

  // 百度OCR格式：提取words_result数组
  if (ocrObj.words_result && Array.isArray(ocrObj.words_result)) {
    return ocrObj.words_result
      .map(item => item.words || '')
      .filter(text => text.trim())
      .join('\n')
      .trim()
  }

  // 通用text字段
  if (ocrObj.text) {
    return ocrObj.text.trim()
  }

  // 如果有subImages数组（阿里云复杂格式）
  if (ocrObj.subImages && Array.isArray(ocrObj.subImages)) {
    let allText = []

    ocrObj.subImages.forEach(subImage => {
      if (subImage.blockInfo && subImage.blockInfo.blockDetails) {
        subImage.blockInfo.blockDetails.forEach(block => {
          if (block.blockContent) {
            allText.push(block.blockContent)
          }
        })
      }
    })

    return allText.join('').trim()
  }

  // 最后尝试直接提取content字段
  return ocrObj.content || ''
}

// 组件挂载时加载历史记录
loadHistory()
</script>

<style scoped>
/* 全局样式 - 现代化设计 */
.search-function {
  min-height: 100%;
  background: transparent;
  padding: 0;
  display: flex;
  flex-direction: column;
  position: relative;
}

.search-function::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 30% 70%, rgba(59, 130, 246, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 70% 30%, rgba(16, 185, 129, 0.08) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

/* 顶部导航栏 */
.search-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  padding: 20px 0;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
  z-index: 100;
}

/* 可滚动主容器 */
.search-main-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
  padding-bottom: 40px; /* 添加底部内边距 */
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

/* 滚动条样式 */
.search-main-container::-webkit-scrollbar {
  width: 6px;
}

.search-main-container::-webkit-scrollbar-track {
  background: transparent;
}

.search-main-container::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 3px;
  transition: background 0.3s ease;
}

.search-main-container::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.5);
}

/* 回到顶部按钮 */
.back-to-top {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  transition: all 0.3s ease;
}

.back-to-top:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  color: #667eea;
}

.page-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  margin: 4px 0 0 0;
  color: #666;
  font-size: 14px;
}

.history-badge {
  margin-right: 8px;
}

/* 主要内容区域 */
.search-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 24px;
}

/* 搜题方式选择卡片 */
.search-modes {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 0 20px;
}

.mode-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  width: 180px;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
}

.mode-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05), rgba(16, 185, 129, 0.05));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.mode-card:hover {
  transform: translateY(-6px) scale(1.02);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.12);
  border-color: rgba(59, 130, 246, 0.3);
}

.mode-card:hover::before {
  opacity: 1;
}

.mode-card.active {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(59, 130, 246, 0.2);
}

.mode-card.active::before {
  opacity: 1;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(16, 185, 129, 0.1));
}

.mode-icon {
  margin-bottom: 12px;
  color: #3b82f6;
  font-size: 32px;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.mode-card:hover .mode-icon {
  color: #1d4ed8;
  transform: scale(1.1);
}

.mode-card.active .mode-icon {
  color: #1d4ed8;
  transform: scale(1.05);
}

.mode-card h3 {
  margin: 0 0 6px 0;
  font-size: 17px;
  font-weight: 700;
  color: #1e293b;
  position: relative;
  z-index: 1;
  transition: color 0.3s ease;
}

.mode-card:hover h3 {
  color: #0f172a;
}

.mode-card p {
  margin: 0;
  color: #64748b;
  font-size: 13px;
  line-height: 1.4;
  position: relative;
  z-index: 1;
  transition: color 0.3s ease;
}

.mode-card:hover p {
  color: #475569;
}

/* 搜题内容区域 */
.search-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  margin-left: 20px;
  margin-right: 20px;
  min-height: 350px;
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
}

/* 拍照搜题样式 */
.camera-section {
  text-align: center;
  width: 100%;
}

.upload-container {
  max-width: 500px;
  margin: 0 auto;
}

.upload-area {
  border: 2px dashed #667eea;
  border-radius: 16px;
  padding: 40px 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(102, 126, 234, 0.05);
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #764ba2;
  background: rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.upload-icon {
  color: #667eea;
  opacity: 0.7;
}

.upload-placeholder h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.upload-placeholder p {
  margin: 0;
  color: #666;
  font-size: 14px;
  text-align: center;
  line-height: 1.4;
}

.upload-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
  justify-content: center;
}

/* 图片预览样式 */
.image-preview {
  text-align: center;
  width: 100%;
}

.preview-container {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;
  max-width: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.image-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
}

.clear-btn {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: none;
  color: #ff4757;
  width: 32px;
  height: 32px;
}

.image-actions, .text-actions {
  text-align: center;
  margin-top: 20px;
}

.search-btn {
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  min-width: 120px;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 文字搜题样式 */
.text-section {
  width: 100%;
  max-width: 100%;
}

.text-input-container {
  text-align: center;
}

.question-textarea {
  border-radius: 12px;
  margin-bottom: 20px;
  width: 100%;
}

.question-textarea :deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  padding: 16px;
  font-size: 15px;
  line-height: 1.5;
  transition: all 0.3s ease;
  min-height: 120px;
  resize: none;
}

.question-textarea :deep(.el-textarea__inner):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 语音搜题样式 */
.voice-section {
  text-align: center;
  max-width: 600px;
  margin: 0 auto;
}

.voice-container {
  padding: 40px 20px;
}

.voice-recorder {
  margin-bottom: 32px;
}

.record-btn {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.record-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 12px 40px rgba(102, 126, 234, 0.4);
}

.voice-recorder.recording .record-btn {
  background: linear-gradient(135deg, #ff4757, #ff3742);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.voice-status h3 {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.voice-result {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 16px;
  padding: 24px;
  margin-top: 24px;
}

.voice-result p {
  margin: 0 0 12px 0;
  font-weight: 600;
  color: #333;
}

.voice-text {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  color: #666;
  font-size: 16px;
  line-height: 1.6;
}

/* 搜题结果样式 - 重新设计 */
.result-section {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  margin: 0 20px 60px 20px; /* 增加底部外边距 */
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f1f5f9;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-icon {
  color: #10b981;
  font-size: 24px;
}

.result-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
}

.result-actions {
  display: flex;
  gap: 4px;
}

.result-actions .el-button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.result-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* OCR识别结果卡片 - 简化版 */
.ocr-result-card {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.ocr-result-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.ocr-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
}

.ocr-icon {
  color: #64748b;
  font-size: 20px;
}

.ocr-title {
  font-size: 16px;
  font-weight: 600;
  color: #334155;
}

.ocr-text-content {
  background: white;
  border-radius: 12px;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  font-size: 16px;
  line-height: 1.8;
  color: #1e293b;
  border: 1px solid #e2e8f0;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
  white-space: pre-wrap;
  word-break: break-word;
  min-height: 60px;
}

/* 题目答案容器 */
.qa-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 32px;
}

.question-section, .answer-section, .analysis-section {
  background: #ffffff;
  border-radius: 16px;
  padding: 24px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.question-section:hover, .answer-section:hover, .analysis-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f1f5f9;
}

.section-icon {
  font-size: 20px;
}

.question-icon {
  color: #3b82f6;
}

.answer-icon {
  color: #10b981;
}

.analysis-icon {
  color: #f59e0b;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.ai-tag {
  margin-left: auto;
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.question-content, .answer-content, .analysis-content {
  color: #374151;
  font-size: 16px;
  line-height: 1.8;
  word-wrap: break-word;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.question-content {
  background: rgba(59, 130, 246, 0.05);
  border-radius: 12px;
  padding: 20px;
  border-left: 4px solid #3b82f6;
  font-weight: 500;
}

.answer-content {
  background: rgba(16, 185, 129, 0.05);
  border-radius: 12px;
  padding: 20px;
  border-left: 4px solid #10b981;
}

.analysis-content {
  background: rgba(245, 158, 11, 0.05);
  border-radius: 12px;
  padding: 20px;
  border-left: 4px solid #f59e0b;
}

/* 内容中的特殊元素样式 */
.question-content strong, .answer-content strong, .analysis-content strong {
  color: #1e293b;
  font-weight: 600;
}

.answer-content p, .analysis-content p {
  margin: 12px 0;
}

.answer-content ul, .analysis-content ul {
  margin: 12px 0;
  padding-left: 20px;
}

.answer-content li, .analysis-content li {
  margin: 6px 0;
}

.related-section {
  margin-top: 32px;
  margin-bottom: 40px; /* 添加底部外边距 */
  background: #ffffff;
  border-radius: 16px;
  padding: 24px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.related-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  display: flex;
  align-items: center;
  gap: 8px;
}

.related-section h3::before {
  content: '💡';
  font-size: 20px;
}

.related-questions {
  display: grid;
  gap: 12px;
}

.related-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
  border-radius: 12px;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
}

.related-item:hover {
  background: rgba(59, 130, 246, 0.05);
  border-color: #3b82f6;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
}

.related-content {
  flex: 1;
  text-align: left;
}

.related-question {
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
  line-height: 1.4;
}

.related-answer {
  color: #666;
  font-size: 13px;
  font-weight: normal;
}

.related-arrow {
  color: #667eea;
  transition: transform 0.3s ease;
  flex-shrink: 0;
}

.related-item:hover .related-arrow {
  transform: translateX(4px);
}

/* 历史记录样式 */
.history-content {
  padding: 20px 0;
}

.empty-history {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-history p {
  margin: 16px 0 0 0;
  font-size: 16px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e1e8ed;
}

.history-item:hover {
  background: rgba(102, 126, 234, 0.05);
  border-color: #667eea;
}

.history-question {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.history-time {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-main {
    padding: 20px 12px;
  }

  .search-modes {
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  .mode-card {
    width: 280px;
    height: 100px;
  }

  .search-content {
    padding: 20px 16px;
    margin: 0 12px 20px 12px;
    min-height: 300px;
  }

  .result-section {
    padding: 20px 16px;
    margin: 0 12px 20px 12px;
  }

  .result-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .result-actions {
    width: 100%;
    justify-content: center;
    flex-wrap: wrap;
  }

  .upload-area {
    padding: 30px 20px;
    height: 200px;
  }

  .upload-placeholder h3 {
    font-size: 18px;
  }

  .upload-placeholder p {
    font-size: 13px;
  }

  .upload-buttons {
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }

  .preview-image {
    max-height: 250px;
  }

  .question-textarea :deep(.el-textarea__inner) {
    min-height: 100px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .search-main {
    padding: 16px 8px;
  }

  .mode-card {
    width: 240px;
    height: 90px;
  }

  .mode-card h3 {
    font-size: 15px;
  }

  .mode-card p {
    font-size: 11px;
  }

  .search-content {
    padding: 16px 12px;
    margin: 0 8px 16px 8px;
    min-height: 280px;
  }

  .result-section {
    padding: 16px 12px;
    margin: 0 8px 16px 8px;
  }

  .upload-area {
    padding: 20px 16px;
    height: 180px;
  }

  .upload-placeholder h3 {
    font-size: 16px;
  }

  .search-btn {
    padding: 10px 20px;
    font-size: 14px;
    min-width: 100px;
  }
}
</style>
